﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;
using UniMana.Utils.Data;
using UniMana.Data;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using UniMana.Win.Personnel;
namespace UniMana.Win.Training
{
    public partial class xucClass : DevExpress.XtraEditors.XtraUserControl
    {
        #region [Khai báo]
        private xucWeek.StyleLoad styleLoad;
        private DataTable pp = new DataTable();
        private DataTable m_dtaScheduler;//, m_dteBackup;
        public DevExpress.Utils.WaitDialogForm dlg;
        
        private int flaSave = -1; 
        //= -1 khởi tạo
        //=  0 Gửi
        //=  1 Sửa
        //=  2 Lưu

        private DateTime m_dStartTime = new DateTime(1, 1, 1);
        private DateTime m_dEndTime = new DateTime(1, 1, 1);

        private int m_iTraining_SubjectOpeRequestKey = -1;
        private int m_iDayOfWeek;
        private int m_iSession;
        private Hashtable m_htbTag;
        private bool m_bIsDragging = false;
        private int m_iTrainingSubjectKey = 0;
        private string m_strSubjectName;
        private List<int> m_lIClassKey;
        private DataTable m_dtaTrainingClass;
        private DataTable m_dtaPersonnel;
        private FrmSchedule_SubChooseTeacher
            frm_FrmSubjectRequestOpen_ChooseTeacher;
        private FrmSchedule_SubChooseDay
            frm_FrmSubjectRequestOpen_ChooseDay;
        private FrmSchedule_SubChooseClass
            frm_SubjectRequestOpen_ChooseClass;
        private FrmSchedule_SubChooseSubject
            frm_SubjectRequestOpen_ChooseSubject;
        private FrmSchedule_SubOpenSubjectClass
            frm_SubjectRequestOpen_OpenSubjectClass;
        private DBMain m_dbTraining = new DBMain();
        private int m_iFrmIndex = 0;
        //private List<FrmSchedule_SubChooseClass>
        //    m_lFrmSubjectRequestOpen_ChooseClass;
        private bool m_bSave = false;

        public delegate void onDelete(xucClass _xucClass);
        public event onDelete OnDelete;
        public delegate void onSave(xucClass _xucClass);
        public event onSave OnSave;
        public delegate void onChangeDay(xucClass _xucClass);
        public event onChangeDay OnChangeDay;
        public delegate void onChooseChange(xucClass _xucClass);
        public event onChooseChange OnChooseChange;

        public DataTable listChildrend;

        private Style m_style;
        private List<Guid> m_lGListPersonnel;

        private DataTable m_dtaClasses;

        private DateTime m_dteStar, m_dteEnd;
        private bool m_bDelete = false;
        #endregion

        #region [Khai Báo, Load]
        public xucClass(
            int _iSession,
            int _iDayofWeek,
            DateTime _dStartTime,
            DateTime _dEndTime)
        {
            InitializeComponent();
            try
            {
                this.m_iDayOfWeek = _iDayofWeek;
                this.m_iSession = _iSession;
                this.m_htbTag = new Hashtable();
                this.m_lIClassKey = new List<int>();
                this.m_lGListPersonnel = new List<Guid>();
                this.m_style = Style.New;
                listChildrend = new DataTable();
                this.LoadData();
                PermissionShow();
                this.btnDelete.Enabled = true;
                this.m_bDelete = true;
                this.btnEdit.Enabled = false;

                this.m_dStartTime = _dStartTime;
                this.m_dEndTime = _dEndTime;

                LUI_BTN_OK.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                LUI_BTN_SEND.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;

                txtSubjectName.Properties.ReadOnly = true;

                layoutControl1.BackColor = SetCol();

                grvTraining_SubjectClass.FocusedRowHandle = 0;
                grvTraining_SubjectClass.Appearance.FocusedRow.BackColor = 
                    SetCol(Convert.ToInt16( 
                    grvTraining_SubjectClass.GetFocusedRowCellValue(gcldep).ToString()));
            }
            catch
            {
            }
        }

        public xucClass(
            DateTime _dStartTime,
            DateTime _dEndTime,
            int _iSession,
            int _iDayofWeek,
            int _iTraining_SubjectOpenRequestKey)
        {
            InitializeComponent();
            try
            {
                this.styleLoad = Cache.m_styleLoad;
                this.m_iTraining_SubjectOpeRequestKey =
                    _iTraining_SubjectOpenRequestKey;
                this.m_style = Style.LoadExist;
                this.m_iDayOfWeek = _iDayofWeek;
                this.m_iSession = _iSession;
                this.m_htbTag = new Hashtable();
                this.m_lIClassKey = new List<int>();
                this.m_lGListPersonnel = new List<Guid>();
                listChildrend = new DataTable();
                this.LoadData();
                this.LoadExistData();
                //this.LUI_BTN_SEND.Visibility =
                //    DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                btnSave.Text = "Sửa";
                this.btnSave.Enabled = true;
                flaSave = 1;
                txtSubjectName.Enabled = false;

                m_iTrainingSubjectKey = -1;
                gluPersonnel_Personnel.Enabled = false;

                this.m_dStartTime = _dStartTime;
                this.m_dEndTime = _dEndTime;

                layoutControl1.BackColor = SetCol();

                grvTraining_SubjectClass.FocusedRowHandle = 0;
                grvTraining_SubjectClass.Appearance.FocusedRow.BackColor = 
                    SetCol(Convert.ToInt16( 
                    grvTraining_SubjectClass.GetFocusedRowCellValue(gcldep).ToString()));                
            }
            catch
            {
            }
        }

        private void LoadData()
        {
            this.m_dtaTrainingClass = new DataTable();
            this.m_dtaTrainingClass.Columns.Add("Training_ClassKey", typeof(int));
            this.m_dtaTrainingClass.Columns.Add("ID", typeof(string));
            this.m_dtaTrainingClass.Columns.Add("Name", typeof(string));
            this.m_dtaTrainingClass.Columns.Add("Totals", typeof(int));
            this.m_dtaTrainingClass.Columns.Add("FrmIndex", typeof(int));
            this.gctTraining_SubjectClass.DataSource = this.m_dtaTrainingClass;

            rptdep.GetData(m_dbTraining.m_DCReadOnly.Training_Classes,"Training_ClassKey","Catalogue_DepartmentKey");

            //this.m_lFrmSubjectRequestOpen_ChooseClass = new List<FrmSchedule_SubChooseClass>();

            #region [Load giảng viên]
            ///
            ///
            DataTable dt = new DataTable();
            dt = this.m_dbTraining.m_DCReadOnly.Personnel_Personnels.GetListTeacher().ToDataTable();
            gluPersonnel_Personnel.GetData(dt,
                "Personnel_PersonnelKey", "FullName");
            rluPersonnel.DataSource = dt;

            rluCatalogue_Department.DataSource = this.m_dbTraining.m_DCReadOnly.Catalogue_Departments;
            rluCatalogue_Department.ValueMember = "Catalogue_DepartmentKey";
            rluCatalogue_Department.DisplayMember = "Name";
            #endregion

            this.gluTraining_Class_Room.GetData(this.m_dbTraining.m_DCReadOnly.Training_Class_Rooms);

            ShowInfo();

            if (this.m_iTraining_SubjectOpeRequestKey != 0)
            {
                DataTable listDay =
                    this.m_dbTraining.m_DCReadOnly.Personnel_Personnel_Sessions.GetSchedulerBySubjectRequestOpen(
                    this.m_iTraining_SubjectOpeRequestKey).ToDataTable();
                if (listDay.Rows.Count > 0)
                {
                    this.m_dtaScheduler = new DataTable();
                    this.m_dtaScheduler.Columns.Add("Date", typeof(DateTime));
                    this.m_dtaScheduler.Columns.Add("WeekOfTerm", typeof(string));
                    this.m_dtaScheduler.Columns.Add("Personnel_PersonnelKey", typeof(Guid));

                    for (int i = 0; i < listDay.Rows.Count; i++)
                    {
                        Guid personnelKey = listDay.Rows[i]["Personnel_PersonnelKey"].ToGuid();
                        DateTime dteDate = listDay.Rows[i]["RegistTime"].ToDateTime();
                        this.m_dtaScheduler.Rows.Add(dteDate, i + 1, personnelKey);
                    }

                    this.gct_Personnel_Personnel_Session.DataSource = this.m_dtaScheduler;
                }
            }
        }
        #endregion

        #region [Thuộc tính]
        public int SubjectKey
        {
            get { return this.m_iTrainingSubjectKey; }
            set
            {
                this.m_iTrainingSubjectKey = value;
            }
        }
        public string SubjectName
        {
            get { return this.m_strSubjectName; }
            set
            {
                this.m_strSubjectName = value;
                this.txtSubjectName.Text = this.m_strSubjectName;
            }
        }
        public int Lessons
        {
            get { return Convert.ToInt16(this.txtLessons.Text); }
            set { this.txtLessons.Text = value.ToString(); }
        }
        public int Credits
        {
            get { return Convert.ToInt16(this.txtLessons.Text); }
            set { this.txtCredits.Text = value.ToString(); }
        }
        public int DayOfWeek
        {
            get { return this.m_iDayOfWeek; }
            set { this.m_iDayOfWeek = value; }
        }
        public int Room
        {
            get
            {
                if (this.gluTraining_Class_Room.EditValue != null)
                {
                    return this.gluTraining_Class_Room.EditValue.ToInt();
                }
                else
                {
                    return 0;
                }
            }
            set { this.gluTraining_Class_Room.EditValue = value; }
        }
        public Hashtable Tag
        {
            get { return this.m_htbTag; }
            set { this.m_htbTag = value; }
        }
        public int Session
        {
            get { return this.m_iSession; }
            set { this.m_iSession = value; }
        }
        public bool Checked
        {
            get { return this.ckeChose.Checked; }
            set { this.ckeChose.Checked = value; }
        }
        public DateTime DteStart
        {
            get { return ((xucSession)this.Parent.Parent).DteStart; }
        }
        public DateTime DteEnd
        {
            get { return ((xucSession)this.Parent.Parent).DteEnd; }
        }
        public List<int> ListClassKey
        {
            get { return this.m_lIClassKey; }
        }

        public int Training_SubjectOpenRequestKey
        {
            get { return this.m_iTraining_SubjectOpeRequestKey; }
        }

        public DataTable ClassesTable
        {
            get { return this.m_dtaClasses; }
        }
        #endregion

        #region [makup]
        private void xucSession_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.DrawLine(Pens.Black,
                new Point(1, 1),
                new Point(this.Width - 1, 1));
            g.DrawLine(Pens.Black,
                new Point(1, 1),
                new Point(1, this.Height - 1));
            g.DrawLine(Pens.Black,
                new Point(1, this.Height - 1),
                new Point(this.Width - 1, this.Height - 1));
            g.DrawLine(Pens.Black,
                new Point(this.Width - 1, this.Height - 1),
                new Point(this.Width - 1, 1));
        }
        private void xucClass_MouseDown(object sender, MouseEventArgs e)
        {
            this.m_bIsDragging = true;
        }
        private void xucClass_MouseUp(object sender, MouseEventArgs e)
        {
            this.m_bIsDragging = false;
        }
        private void xucClass_MouseLeave(object sender, EventArgs e)
        {
            this.m_bIsDragging = false;
        }
        private void xucClass_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_bIsDragging)
            {
                DoDragDrop(this, DragDropEffects.Move);
            }
        }
        private void btnSelectSubject_Click(object sender, EventArgs e)
        {
            ChoseSubject();
        }
        #endregion

        #region [Chọn lớp - Danh sách SV]
        private void grvgctTraining_SubjectClass_DoubleClick(object sender, EventArgs e)
        {
            //try
            {

                if (m_iTrainingSubjectKey > 0)
                {
                    if (this.m_style == Style.New)
                    {
                        #region [Add mới]
                        GridView view = (GridView)sender;
                        Point pt = view.GridControl.PointToClient(Control.MousePosition);
                        GridHitInfo info = view.CalcHitInfo(pt);
                        FrmSchedule_SubChooseClass frm_SubjectRequestOpen_ChooseClass = null;
                        if (!info.InRow)
                        {
                            frm_SubjectRequestOpen_ChooseClass = new FrmSchedule_SubChooseClass();
                        }
                        //else
                        //{
                        //    if (this.m_lFrmSubjectRequestOpen_ChooseClass.Count > 0)
                        //    {
                        //        int FrmIndex =
                        //            this.grvTraining_SubjectClass.GetRowCellValue(
                        //            info.RowHandle,
                        //            this.gclFrmIndex).ToInt();
                        //        frm_SubjectRequestOpen_ChooseClass =
                        //            this.m_lFrmSubjectRequestOpen_ChooseClass[FrmIndex];
                        //    }
                        //    else
                        //    {

                        //    }
                        //}

                        //if (frm_SubjectRequestOpen_ChooseClass != null)
                        //{
                        //    for (int i = 0; i < Cache.m_dtaClass_Student.Rows.Count; i++)
                        //    {

                        //    }
                        //        frm_SubjectRequestOpen_ChooseClass.ShowDialog();

                        //    if (frm_SubjectRequestOpen_ChooseClass.DialogResult == DialogResult.OK)
                        //    {
                        //        if (!info.InRow)
                        //        {
                        //            this.m_lFrmSubjectRequestOpen_ChooseClass.Add(
                        //                frm_SubjectRequestOpen_ChooseClass);
                        //            if (this.m_lIClassKey.IndexOf(
                        //                frm_SubjectRequestOpen_ChooseClass.TrainingClassKey) > -1)
                        //            {
                        //                XtraMessageBox.Show("Lớp này đã thêm vào danh sách");
                        //                return;
                        //            }
                        //        }

                        //        int iFrmIndex = -1;
                        //        if (info.InRow)
                        //        {
                        //            this.m_lIClassKey.Remove(frm_SubjectRequestOpen_ChooseClass.TrainingClassKey);

                        //            for (int i = 0; i < this.m_dtaTrainingClass.Rows.Count; i++)
                        //            {
                        //                if (this.m_dtaTrainingClass.Rows[i]["Training_ClassKey"].ToInt() ==
                        //                    frm_SubjectRequestOpen_ChooseClass.TrainingClassKey)
                        //                {
                        //                    iFrmIndex = this.m_dtaTrainingClass.Rows[i]["FrmIndex"].ToInt();
                        //                    this.m_dtaTrainingClass.Rows.RemoveAt(i);
                        //                    break;
                        //                }
                        //            }
                        //        }
                        //        else
                        //        {
                        //            iFrmIndex = this.m_iFrmIndex;
                        //            this.m_iFrmIndex++;
                        //        }
                        //        this.m_lIClassKey.Add(
                        //            frm_SubjectRequestOpen_ChooseClass.TrainingClassKey);
                        //        Training_ClassInfo classInfo = new Training_ClassInfo(
                        //            frm_SubjectRequestOpen_ChooseClass.TrainingClassKey);
                        //        if (classInfo.ExistInDataBase)
                        //        {
                        //            this.m_dtaTrainingClass.Rows.Add(
                        //                classInfo.Properties.Training_ClassKey,
                        //                classInfo.Properties.ID,
                        //                classInfo.Properties.Name,
                        //                frm_SubjectRequestOpen_ChooseClass.TotalStudent,
                        //                iFrmIndex);
                        //        }
                        //    }
                        //}
                        #endregion
                    }
                    else
                    {
                        #region [Xem lại lớp cũ]

                        #endregion
                    }
                    LUI_BTN_SEND.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                }
                else
                {
                    XtraMessageBox.Show("Chưa Chọn Môn", "Thông Báo");
                }
            }
            //catch
            {
            }
        }
        #endregion

        #region [Chọn lịch giảng]
        private void gct_Personnel_Personnel_Session_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (!SysUtils.CheckEditByRule("R023"))
                {
                    //XtraMessageBox.Show("Bạn không có quyền này");
                    return;
                }
                if (this.m_lGListPersonnel.Count > 0)
                {
                    if (frm_FrmSubjectRequestOpen_ChooseDay == null)
                    {
                        if (m_iTraining_SubjectOpeRequestKey == -1)
                        {
                            frm_FrmSubjectRequestOpen_ChooseDay =
                                new FrmSchedule_SubChooseDay(
                                this.m_iDayOfWeek,
                                this.m_iSession,
                                this.m_lGListPersonnel,
                                this.m_dteStar,
                                this.m_dteEnd);
                        }
                        else
                        {
                            frm_FrmSubjectRequestOpen_ChooseDay =
                                new FrmSchedule_SubChooseDay(
                                this.m_iDayOfWeek,
                                this.m_iSession,
                                this.m_lGListPersonnel,
                                this.m_dteStar,
                                this.m_dteEnd,
                                this.m_iTraining_SubjectOpeRequestKey);
                        }
                    }
                    else
                    {
                    }

                    frm_FrmSubjectRequestOpen_ChooseDay.OnResume(this.m_lGListPersonnel);
                    frm_FrmSubjectRequestOpen_ChooseDay.ShowDialog();
                    if (frm_FrmSubjectRequestOpen_ChooseDay.DialogResult == DialogResult.OK ||
                        frm_FrmSubjectRequestOpen_ChooseDay.DialogResult == DialogResult.Cancel)
                    {
                        if (this.m_style == Style.LoadExist)
                        {
                            this.m_dbTraining.m_DCReadOnly.Personnel_Personnel_Sessions.ClearPersonnelSession(
                                this.m_iTraining_SubjectOpeRequestKey);
                            DataTable listChooseDay = frm_FrmSubjectRequestOpen_ChooseDay.ListChooseDay;
                            for (int i = 0; i < listChooseDay.Rows.Count; i++)
                            {
                                DateTime registTime = listChooseDay.Rows[i]["Date"].ToDateTime();
                                Guid personnelKey = listChooseDay.Rows[i]["Personnel_PersonnelKey"].ToGuid();
                                Personnel_Personnel_SessionInfo personelSessionInfo =
                                    new Personnel_Personnel_SessionInfo(
                                    personnelKey, this.m_iDayOfWeek + 1, this.m_iSession, registTime);
                                if (personelSessionInfo.ExistInDataBase)
                                {
                                    personelSessionInfo.Properties.Status = true;
                                    personelSessionInfo.Properties.Training_SubjectOpenRequestKey =
                                        this.m_iTraining_SubjectOpeRequestKey;
                                    personelSessionInfo.Save();
                                }
                            }
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("Chưa chọn giảng viên");
                }
            }
            catch
            {
            }
        }
        #endregion

        #region [Chọn giảng viên]
        private void gluPersonnel_Personnel_EditValueChanged(
            object sender,
            EventArgs e)
        {
            try
            {
                this.m_lGListPersonnel.Clear();
                this.m_lGListPersonnel.Add(
                    this.gluPersonnel_Personnel.EditValue.ToGuid());
            }
            catch
            {
            }
        }
        #endregion

        #region [ Xóa dữ liệu]
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //try
            {
                if (this.m_style == Style.New)
                {
                    if (OnDelete != null) OnDelete(this);
                    return;
                }
                if (!SysUtils.CheckDeleteByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    //XtraMessageBox.Show("Bạn không có quyền này");
                    return;
                }
                #region [Xóa dữ liệu]
                if (this.m_style == Style.LoadExist)
                {
                    if (DialogResult.Yes != XtraMessageBox.Show(
                        "Bạn có chắc chắn hay không",
                        "Xác nhận",
                        MessageBoxButtons.YesNo))
                    {
                        return;
                    }

                    int iTraining_SubjectOpenRequestKey = this.m_iTraining_SubjectOpeRequestKey;

                    DataTable list =
                            this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequests.GetListChildrent(
                                iTraining_SubjectOpenRequestKey,
                                true).ToDataTable();

                    for (int k = 0; k < list.Rows.Count; k++)
                    {
                        Training_SubjectOpenRequestInfo infoRequest =
                            new Training_SubjectOpenRequestInfo(
                                Convert.ToInt16(
                                    list.Rows[k]["Training_SubjectOpenRequestKey"].ToString()));

                        if (infoRequest.ExistInDatabase)
                        {
                            #region [Xóa lớp HP - Xóa SV lớp HP ]
                            DataTable listSubjectClass =
                                this.m_dbTraining.m_DCReadOnly.Training_Subject_Classes.GetSubjectClassBySubjectOpenRequest(
                                    Convert.ToInt16(
                                        list.Rows[k]["Training_SubjectOpenRequestKey"].ToString())).ToDataTable();
                            for (int i = 0; i < listSubjectClass.Rows.Count; i++)
                            {
                                int iTraining_SubjectClassKey =
                                    listSubjectClass.Rows[i]["Training_Subject_ClassKey"].ToInt();
                                this.m_dbTraining.m_DCReadOnly.Training_Student_Subject_Classes.DeleteByClassKey(
                                    iTraining_SubjectClassKey);
                                Training_Subject_ClassInfo classInfo =
                                    new Training_Subject_ClassInfo(
                                        iTraining_SubjectClassKey);
                                classInfo.Delete();
                                classInfo.Save();
                            }
                            #endregion

                            #region [Xóa SV_GV]
                            this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequest_Teacher_Students.
                                    DeleteBySubjectOpenRequestKey(
                                Convert.ToInt16(
                                    list.Rows[k]["Training_SubjectOpenRequestKey"].ToString()));
                            #endregion

                            #region [Xóa danh sách sv đăng ký môn]
                            this.m_dbTraining.m_DCReadOnly.Training_Student_Subjects.
                                    DeleteStudentSubjectByRequestOpenKey(
                                Convert.ToInt16(
                                    list.Rows[k]["Training_SubjectOpenRequestKey"].ToString()));
                            #endregion

                            #region [Xóa mở môn]
                            //Chỉ có 1 yêu cầu môn này thì xóa
                            if (this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequests.
                                    GetListByDateTimeAndSubject(
                                        this.DteStart,
                                        this.DteEnd,
                                        this.m_iTrainingSubjectKey).ToDataTable().Rows.Count <= 1)
                            {
                                Training_Subject_OpenInfo subjectOpenInfo = new Training_Subject_OpenInfo(
                                    this.m_iTrainingSubjectKey, true);
                                subjectOpenInfo.Delete();
                                subjectOpenInfo.Save();
                            }
                            #endregion

                            #region [Xóa đăng ký lịch giảng]
                            this.m_dbTraining.m_DCReadOnly.Personnel_Personnel_Sessions.ClearPersonnelSession(
                                Convert.ToInt16(
                                    list.Rows[k]["Training_SubjectOpenRequestKey"].ToString()));
                            #endregion

                            #region [Xóa yêu cầu mở môn]
                            infoRequest.Delete();
                            infoRequest.Save();
                            #endregion
                        }
                    }
                    if (OnDelete != null) OnDelete(this);
                }
                #endregion
            }
            //catch
            {
            }
        }
        #endregion

        #region [Lưu - Gửi yêu cầu]
        private void btnSave_Click(object sender, EventArgs e)
        {
            //try
            {
                if (this.flaSave != 1)
                {
                    #region [Điều Kiện]
                    if (!SysUtils.CheckAddByRule(
                        Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                    {
                        XtraMessageBox.Show("Bạn không có quyền này");
                        return;
                    }

                    if (!this.ckeCreateSubjectClass.Checked)
                    {
                        if (XtraMessageBox.Show("Yêu cầu này không tạo bảng điểm?",
                            "Xác nhận",
                            MessageBoxButtons.YesNo) == DialogResult.No)
                        {
                            return;
                        }
                    }
                    if (this.SubjectKey == 0)
                    {
                        XtraMessageBox.Show("Chưa chọn môn học");
                        return;
                    }
                    if (this.txtSubjectName.Text == "")
                    {
                        XtraMessageBox.Show("Tên môn học không được để trống");
                        return;
                    }
                    if (this.grvTraining_SubjectClass.RowCount == 0)
                    {
                        XtraMessageBox.Show("Chưa chọn lớp và sinh viên");
                        return;
                    }
                    if (OnSave != null) OnSave(this);
                    #endregion

                    #region [Khởi tạo giá trị truyền]
                    this.m_bSave = true;
                    Guid gPersonnelKey = this.gluPersonnel_Personnel.EditValue.ToGuid();
                    int iDayOfWeek = this.m_iDayOfWeek;
                    int iSession = this.m_iSession;
                    double dCredits = this.txtCredits.Text.Split(' ')[0].ToDouble();
                    int iLesson = this.txtLessons.Text.Split(' ')[0].ToInt();
                    bool bCredit1 = this.ckeTheory.Checked;
                    bool bCredit3 = this.ckePractice.Checked;
                    int iRoom = this.gluTraining_Class_Room.EditValue.ToInt();
                    string strTraining_SubjectName = this.txtSubjectName.Text;
                    m_dtaTrainingClass.Columns.Add("Training_SubjectKey");
                    m_dtaTrainingClass.Columns.Add("Training_SubjectID");
                    m_dtaTrainingClass.Columns.Add("Training_SubjectName");

                    int samekey = -1;
                    try
                    {
                        DataTable dt = new DataTable();
                        dt = m_dbTraining.m_DCReadOnly.Training_Subjects.GetBySubjectKey(
                            m_iTrainingSubjectKey).ToDataTable();
                        samekey = Convert.ToInt16(dt.Rows[0]["Subject_SameKey"].ToString());
                    }
                    catch
                    {
                    }

                    for (int i = 0; i < m_dtaTrainingClass.Rows.Count; i++)
                    {
                        DataTable dt = new DataTable();
                        int subjectkey = -1;
                        string subjectID = "";
                        string subjectName = "";
                        dt = m_dbTraining.m_DCReadOnly.Training_Subjects.GetListByClassKey(
                                m_dbTraining.m_DCReadOnly.Training_TrainingProgram_Details,
                                m_dbTraining.m_DCReadOnly.Training_Classes,
                                Convert.ToInt16(m_dtaTrainingClass.Rows[i]["Training_ClassKey"].ToString()),
                                m_iTrainingSubjectKey,
                                samekey).ToDataTable();
                        if (dt.Rows.Count > 0)
                        {
                            subjectkey = Convert.ToInt16(dt.Rows[0]["Training_SubjectKey"].ToString());
                            subjectID = dt.Rows[0]["ID"].ToString();
                            subjectName = dt.Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            subjectkey = m_iTrainingSubjectKey;
                        }

                        m_dtaTrainingClass.Rows[i]["Training_SubjectKey"] = subjectkey;
                        m_dtaTrainingClass.Rows[i]["Training_SubjectID"] = subjectID;
                        m_dtaTrainingClass.Rows[i]["Training_SubjectName"] = subjectName;
                    }

                    int _iCouserKey = this.frm_SubjectRequestOpen_ChooseSubject.CouserKey;
                    int iDepartmentKey = this.frm_SubjectRequestOpen_ChooseSubject.DepartmentKey;
                    int _iTrainingProgramKey = this.frm_SubjectRequestOpen_ChooseSubject.TrainingProgramKey;
                    bool bCreateSubjectClass = this.ckeCreateSubjectClass.Checked;
                    string txtNote = this.txtNote.Text;

                    #endregion
                    #region [Gọi Form]
                    if (dCredits == 0 || iLesson == 0)
                    {
                        XtraMessageBox.Show("Số tín chỉ, hoặc số tiết không được để trống");
                        return;
                    }

                    //if (frm_SubjectRequestOpen_OpenSubjectClass == null)
                    //{
                    //    this.frm_SubjectRequestOpen_OpenSubjectClass =
                    //        new FrmSchedule_SubOpenSubjectClass(
                    //            this.m_dtaTrainingClass,
                    //            this.m_lFrmSubjectRequestOpen_ChooseClass);
                    //}
                    this.frm_SubjectRequestOpen_OpenSubjectClass.ShowDialog();
                    #endregion

                    if (this.frm_SubjectRequestOpen_OpenSubjectClass.DialogResult == DialogResult.OK)
                    {
                        int parentkey = -1;
                        for (int f = 0; f < m_dtaTrainingClass.Rows.Count; f++)
                        {
                            #region [Lưu yêu cầu mở môn]
                            Training_SubjectOpenRequestInfo info = new Training_SubjectOpenRequestInfo();
                            if (gPersonnelKey.ToString() != "00000000-0000-0000-0000-000000000000")
                            {
                                info.Properties.Personnel_PersonnelTeacherKey = gPersonnelKey;
                            }
                            info.Properties.Training_WeekDayKey = iDayOfWeek;
                            info.Properties.Training_SessionKey = iSession;
                            info.Properties.Training_Class_RoomKey = iRoom;
                            info.Properties.Credits = dCredits;
                            info.Properties.Lessons = iLesson;
                            info.Properties.Training_SubjectKey =
                                Convert.ToInt16(m_dtaTrainingClass.Rows[f]["Training_SubjectKey"].ToString());
                            info.Properties.Training_SubjecName = m_strSubjectName;
                            info.Properties.Credit1 = bCredit1;
                            info.Properties.Credit3 = bCredit3;
                            info.Properties.AgreeOpen = true;
                            info.Properties.Active = true;
                            info.Properties.Startus = 0;
                            info.Properties.Catalogue_CourseKey = _iCouserKey;
                            info.Properties.Catalogue_DepartmentKey = iDepartmentKey;
                            info.Properties.Training_TrainingProgramKey = _iTrainingProgramKey;

                            DateTime now = SysDateTime.Now;
                            info.Properties.CreateOn = now;
                            info.Properties.Personnel_PersonnelRequestKey =
                                UniMana.Utils.LoginInfo.GblLoginInfo.sysLoginPersionalKey;
                            info.Properties.CreateSubjectClass = bCreateSubjectClass;
                            info.Properties.Note = txtNote;
                            if (parentkey != -1)
                            {
                                info.Properties.Training_SubjectOpenRequestKeyParent = parentkey;
                            }
                            info.Save();

                            this.m_iTraining_SubjectOpeRequestKey =
                                info.Properties.Training_SubjectOpenRequestKey;
                            if (parentkey == -1)
                            {
                                parentkey = info.Properties.Training_SubjectOpenRequestKey;
                            }
                            #endregion

                            #region [Lưu đăng ký lịch giảng]

                            #region [Xóa dữ liệu cũ]
                            if (frm_FrmSubjectRequestOpen_ChooseDay != null)
                            {
                                if (frm_FrmSubjectRequestOpen_ChooseDay.ListDayBackup != null)
                                {
                                    this.m_dbTraining.m_DCReadOnly.Personnel_Personnel_Sessions.ClearPersonnelSession(
                                        this.m_iTraining_SubjectOpeRequestKey);
                                    //DataTable listDayBackup = frm_FrmSubjectRequestOpen_ChooseDay.ListDayBackup;
                                    //for (int i = 0; i < this.m_lGListPersonnel.Count; i++)
                                    //{
                                    //    DateTime registTime = listDayBackup.Rows[i]["Date"].ToDateTime();
                                    //    Guid personnelKey = listDayBackup.Rows[i]["Personnel_PersonnelKey"].ToGuid();
                                    //    Personnel_Personnel_SessionInfo personelSessionInfo = new Personnel_Personnel_SessionInfo(
                                    //personnelKey, 
                                    //this.m_iDayOfWeek, 
                                    //this.m_iSession, 
                                    //registTime);
                                    //    if (personelSessionInfo.ExistInDataBase)
                                    //    {
                                    //        personelSessionInfo.Delete();
                                    //        personelSessionInfo.Save();
                                    //    }
                                    //}
                                }
                            }
                            #endregion

                            #region [Lưu dữ liệu mới]
                            if (frm_FrmSubjectRequestOpen_ChooseDay != null)
                            {
                                if (frm_FrmSubjectRequestOpen_ChooseDay.ListChooseDay != null)
                                {
                                    DataTable listChooseDay =
                                        frm_FrmSubjectRequestOpen_ChooseDay.ListChooseDay;
                                    for (int i = 0; i < listChooseDay.Rows.Count; i++)
                                    {
                                        DateTime registTime =
                                            listChooseDay.Rows[i]["Date"].ToDateTime();
                                        Guid personnelKey =
                                            listChooseDay.Rows[i]["Personnel_PersonnelKey"].ToGuid();
                                        Personnel_Personnel_SessionInfo personelSessionInfo =
                                            new Personnel_Personnel_SessionInfo(
                                                personnelKey,
                                                this.m_iDayOfWeek + 1,
                                                this.m_iSession,
                                                registTime);
                                        if (personelSessionInfo.ExistInDataBase)
                                        {
                                            personelSessionInfo.Properties.Status = true;
                                            personelSessionInfo.Properties.Training_SubjectOpenRequestKey =
                                                info.Properties.Training_SubjectOpenRequestKey;
                                            personelSessionInfo.Save();
                                        }
                                    }
                                }
                            }
                            #endregion

                            #endregion

                            //#region [Lưu danh sách sinh viên thuộc lớp - Training_SubjectOpenRequest_Teacher_StudentInfo]
                            //int iTrainingProgramKey =
                            //    this.m_lFrmSubjectRequestOpen_ChooseClass[f].TrainingProgramKey;
                            //int iTrainingClassKey =
                            //    this.m_lFrmSubjectRequestOpen_ChooseClass[f].TrainingClassKey;
                            //for (int j = 0; j <
                            //    this.m_lFrmSubjectRequestOpen_ChooseClass[f].ListStudent.Rows.Count; j++)
                            //{
                            //    DataRow row =
                            //        this.m_lFrmSubjectRequestOpen_ChooseClass[f].ListStudent.Rows[j];
                            //    Training_SubjectOpenRequest_Teacher_StudentInfo teacherStudentInfo =
                            //        new Training_SubjectOpenRequest_Teacher_StudentInfo(
                            //            info.Properties.Training_SubjectOpenRequestKey,
                            //            row["Training_StudentKey"].ToString(),
                            //            iTrainingProgramKey);
                            //    if (!teacherStudentInfo.ExistInDatabase)
                            //    {
                            //        teacherStudentInfo.Properties.Training_ClassKey =
                            //            iTrainingClassKey;
                            //        teacherStudentInfo.Save();
                            //    }
                            //}
                            //#endregion

                            #region [Mở lớp học phần => Đưa sv vào - Đăng ký môn học]
                            if (this.ckeCreateSubjectClass.Checked)
                            {
                                DataTable dt =
                                    this.frm_SubjectRequestOpen_OpenSubjectClass.DataClassInfo;
                                //int iCouserKey =
                                //        this.m_lFrmSubjectRequestOpen_ChooseClass[f].CouserKey;
                                int iSchoolYearKey =
                                    dt.Rows[f]["Catalogue_SchoolYearKey"].ToInt();
                                int iTermKey =
                                    dt.Rows[f]["Catalogue_TermKey"].ToInt();
                                //this.m_dbTraining.m_DCReadOnly.Catalogue_Course_SchoolYear_Terms.GetSchoolYear_TermByCourse_Year(
                                //iCouserKey, 
                                //ref iSchoolYearKey, 
                                //ref iTermKey);

                                string strSubjectClassID =
                                    dt.Rows[f]["SubjectClassID"].ToString();
                                string strSubjectClassName =
                                    dt.Rows[f]["SubjectClassName"].ToString();

                                #region [Tạo lớp học phần]
                                //Training_ClassInfo classInfo =
                                //    new Training_ClassInfo(
                                //        this.m_lFrmSubjectRequestOpen_ChooseClass[f].TrainingClassKey);
                                //bool bYearly = false;
                                //if (classInfo.Properties.Yearly == null)
                                //{
                                //    bYearly = true;
                                //}
                                //else
                                //{
                                //    bYearly = classInfo.Properties.Yearly.Value;
                                //}

                                //Training_Subject_ClassInfo subjectClassInfo =
                                //    new Training_Subject_ClassInfo(0);
                                //subjectClassInfo.Properties.ID = strSubjectClassID;
                                //subjectClassInfo.Properties.Name = strSubjectClassName;
                                //subjectClassInfo.Properties.Opened = true;
                                //subjectClassInfo.Properties.Catalogue_TermKey = iTermKey;
                                //subjectClassInfo.Properties.Catalogue_SchoolYearKey =
                                //    iSchoolYearKey;
                                //subjectClassInfo.Properties.Personnel_PersonnelKey =
                                //    info.Properties.Personnel_PersonnelTeacherKey;
                                //subjectClassInfo.Properties.Training_ClassKey =
                                //    dt.Rows[f]["Training_ClassKey"].ToInt();
                                //subjectClassInfo.Properties.Training_SubjectKey =
                                //    Convert.ToInt16(m_dtaTrainingClass.Rows[f]["Training_SubjectKey"].ToString());
                                //subjectClassInfo.Properties.Training_SubjectOpenRequestKey =
                                //    info.Properties.Training_SubjectOpenRequestKey;
                                //subjectClassInfo.Properties.Yearly = bYearly;
                                //subjectClassInfo.Save();
                                //#endregion

                                //#region [Tạo loại điểm cho lớp học phần]
                                //int iSubjectClassKey =
                                //    subjectClassInfo.Properties.Training_Subject_ClassKey;

                                //if (bYearly)
                                //{
                                //    //Lớp niên chế
                                //    if (classInfo.Properties.Catalogue_LevelKey ==
                                //        (int)UniMana.Utils.Configs.DefaultConfig.Catalogue_Level.Intermediate)
                                //    {
                                //        //Lớp cho trung cấp
                                //        int iSubjectKey = this.SubjectKey;
                                //        Training_SubjectInfo subjectInfo = new Training_SubjectInfo(iSubjectKey);

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_FrequentlyTest1 =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.FrequentlyTest1);
                                //        subjectClassScoreTypeinfo_FrequentlyTest1.Properties.DefaultPercent = 0;
                                //        subjectClassScoreTypeinfo_FrequentlyTest1.Save();

                                //        if (subjectInfo.Properties.TotalCredits.Value > 3)
                                //        {
                                //            Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_FrequentlyTest2 =
                                //                new Training_SubjectClass_ScoreTypeInfo(
                                //                    iSubjectClassKey,
                                //                    (int)Utils.Configs.DefaultConfig.ScoreType.FrequentlyTest2);
                                //            subjectClassScoreTypeinfo_FrequentlyTest2.Properties.DefaultPercent = 0;
                                //            subjectClassScoreTypeinfo_FrequentlyTest2.Save();
                                //        }

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_PeriodicallyTest1 =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.PeriodicallyTest1);
                                //        subjectClassScoreTypeinfo_PeriodicallyTest1.Properties.DefaultPercent = 0;
                                //        subjectClassScoreTypeinfo_PeriodicallyTest1.Save();

                                //        if (subjectInfo.Properties.TotalCredits.Value > 3)
                                //        {
                                //            Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_PeriodicallyTest2 =
                                //                new Training_SubjectClass_ScoreTypeInfo(
                                //                    iSubjectClassKey,
                                //                    (int)Utils.Configs.DefaultConfig.ScoreType.PeriodicallyTest2);
                                //            subjectClassScoreTypeinfo_PeriodicallyTest2.Properties.DefaultPercent = 0;
                                //            subjectClassScoreTypeinfo_PeriodicallyTest2.Save();
                                //        }

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_FinalTest =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.FinalTest);
                                //        subjectClassScoreTypeinfo_FinalTest.Properties.DefaultPercent = 0;
                                //        subjectClassScoreTypeinfo_FinalTest.Save();

                                //    }
                                //    else
                                //    {
                                //        //Lớp cho đại học - Cao đẳng

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_MidTerm =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.MidTerm);
                                //        subjectClassScoreTypeinfo_MidTerm.Properties.DefaultPercent = 30;
                                //        subjectClassScoreTypeinfo_MidTerm.Save();

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_EndTerm1 =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.EndTerm1);
                                //        subjectClassScoreTypeinfo_EndTerm1.Properties.DefaultPercent = 70;
                                //        subjectClassScoreTypeinfo_EndTerm1.Save();

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_EndTerm2 =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.EndTerm2);
                                //        subjectClassScoreTypeinfo_EndTerm2.Properties.DefaultPercent = 70;
                                //        subjectClassScoreTypeinfo_EndTerm2.Save();

                                //    }
                                //}
                                //else
                                //{
                                //    //Lớp theo tín chỉ , Lớp học phần
                                //    if (classInfo.Properties.Catalogue_LevelKey ==
                                //        (int)UniMana.Utils.Configs.DefaultConfig.Catalogue_Level.Colleges ||
                                //        classInfo.Properties.Catalogue_LevelKey ==
                                //            (int)UniMana.Utils.Configs.DefaultConfig.Catalogue_Level.University)
                                //    {
                                //        //Đại học - Cao đẳng
                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_MidTerm =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.MidTerm);
                                //        subjectClassScoreTypeinfo_MidTerm.Properties.DefaultPercent = 40;
                                //        subjectClassScoreTypeinfo_MidTerm.Save();

                                //        Training_SubjectClass_ScoreTypeInfo subjectClassScoreTypeinfo_EndTerm1 =
                                //            new Training_SubjectClass_ScoreTypeInfo(
                                //                iSubjectClassKey,
                                //                (int)Utils.Configs.DefaultConfig.ScoreType.EndTerm1);
                                //        subjectClassScoreTypeinfo_EndTerm1.Properties.DefaultPercent = 60;
                                //        subjectClassScoreTypeinfo_EndTerm1.Save();
                                //    }
                                //}
                                //subjectClassInfo.Save();

                                #endregion

                                #region [Mở môn học]

                                Training_Subject_OpenInfo subjectOpenInfo =
                                    new Training_Subject_OpenInfo(
                                        Convert.ToInt16(
                                            m_dtaTrainingClass.Rows[f]["Training_SubjectKey"].ToString()),
                                        true);
                                if (!subjectOpenInfo.ExistInDataBase)
                                {
                                    subjectOpenInfo.Properties.MinimumRegist = 60;
                                    subjectOpenInfo.Properties.Period = 7;
                                    subjectOpenInfo.Properties.BeginTimeRegist = now;
                                    subjectOpenInfo.Properties.Closed = false;
                                    subjectOpenInfo.Save();
                                    info.Properties.Training_SubjectOpenKey =
                                        subjectOpenInfo.Properties.Training_SubjectOpenKey;
                                }

                                #endregion

                                #region [Đưa sinh viên vào lớp học phần - Đăng ký môn]

                                int iTraining_ClassKey = dt.Rows[f]["Training_ClassKey"].ToInt();
                                DateTime dtNow = SysDateTime.Now;
                                //for (int j = 0; j < this.m_lFrmSubjectRequestOpen_ChooseClass.Count; j++)
                                //{
                                //    if (iTraining_ClassKey ==
                                //        this.m_lFrmSubjectRequestOpen_ChooseClass[j].TrainingClassKey)
                                //    {
                                //        DataTable listStudent =
                                //            this.m_lFrmSubjectRequestOpen_ChooseClass[j].ListStudent;

                                //        for (int k = 0; k < listStudent.Rows.Count; k++)
                                //        {
                                //            Guid gStudentKey =
                                //                listStudent.Rows[k]["Training_StudentKey"].ToGuid();
                                //            int iTraining_ProgramKey =
                                //                listStudent.Rows[k]["Training_TrainingProgramKey"].ToInt();
                                //            #region [Đưa vào lớp học phần]
                                //            Training_Student_Subject_ClassInfo studentSubjectClassInfo =
                                //                new Training_Student_Subject_ClassInfo(
                                //                    iSubjectClassKey,
                                //                    gStudentKey.ToString(),
                                //                    iTraining_ProgramKey);
                                //            studentSubjectClassInfo.Properties.CreatedOn = dtNow;
                                //            studentSubjectClassInfo.Properties.CreatedBy =
                                //                Utils.LoginInfo.GblLoginInfo.sysLoginPersionalKey;
                                //            studentSubjectClassInfo.Properties.Training_SubjectOpenKey =
                                //                subjectOpenInfo.Properties.Training_SubjectOpenKey;
                                //            studentSubjectClassInfo.Save();
                                //            #endregion

                                //            #region [Đưa vào SV đăng ký môn]
                                //            Training_Student_SubjectInfo studentSubjectInfo =
                                //                new Training_Student_SubjectInfo();
                                //            studentSubjectInfo.Properties.Training_StudentKey = gStudentKey;
                                //            studentSubjectInfo.Properties.Training_SubjectKey =
                                //                Convert.ToInt16(m_dtaTrainingClass.Rows[f]["Training_SubjectKey"].ToString());
                                //            studentSubjectInfo.Properties.RegistTime = now;
                                //            studentSubjectInfo.Properties.Training_Student_Subject_Regist_TypeKey =
                                //                (int)UniMana.Utils.Configs.DefaultConfig.Subject_Regist_TypeKey.Score_FirstCore;
                                //            studentSubjectInfo.Properties.Training_SubjectOpenKey =
                                //                subjectOpenInfo.Properties.Training_SubjectOpenKey;
                                //            studentSubjectInfo.Properties.Training_TrainingProgramKey =
                                //                iTraining_ProgramKey;
                                //            studentSubjectInfo.Properties.Training_SubjectOpenRequestKey =
                                //                info.Properties.Training_SubjectOpenRequestKey;
                                //            studentSubjectInfo.Save();
                                //            #endregion
                                //        }
                                //    }
                                //}
                                #endregion
                            }
                            #endregion
                        }
                        this.btnDelete.Enabled = true;
                        this.btnEdit.Enabled = true;

                        m_iTrainingSubjectKey = -1;
                        gluPersonnel_Personnel.Enabled = false;

                        btnSave.Text = "Sửa";
                        this.btnSave.Enabled = true;
                        flaSave = 1;

                        LUI_BTN_OK.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    }
                }
                else
                {
                    Training_SubjectOpenRequestInfo sjorq =
                        new Training_SubjectOpenRequestInfo(m_iTraining_SubjectOpeRequestKey);
                    m_iTrainingSubjectKey = Convert.ToInt16(sjorq.Properties.Training_SubjectKey.ToString());

                    gluPersonnel_Personnel.Enabled = true;

                    this.btnSave.Enabled = true;
                    btnSave.Text = "Lưu";
                    flaSave = 2;
                }
            }
            //catch
            {
            }
        }
        #endregion

        #region [Load dữ liệu cũ]
        private void LoadExistData()
        {
            try
            {
                int iTraining_SubjectOpenRequestKey = this.m_iTraining_SubjectOpeRequestKey;
                Training_SubjectOpenRequestInfo openReqestInfo =
                    new Training_SubjectOpenRequestInfo(iTraining_SubjectOpenRequestKey);
                if (openReqestInfo.ExistInDatabase)
                {
                    this.txtSubjectName.Text = openReqestInfo.Properties.Training_SubjecName;
                    this.SubjectKey = openReqestInfo.Properties.Training_SubjectKey.Value;
                    DataTable dt =
                        this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequest_Teacher_Students.GetByReuqestOpenKey(
                        this.m_dbTraining.m_DCReadOnly.Training_Classes,
                        iTraining_SubjectOpenRequestKey).ToDataTable();
                    dt.Columns.Add("FrmIndex", typeof(int));
                    this.m_dtaClasses = dt;

                    this.m_dtaTrainingClass = dt;
                    this.gctTraining_SubjectClass.DataSource = this.m_dtaTrainingClass;
                    if (openReqestInfo.Properties.Personnel_PersonnelTeacherKey != null)
                    {
                        this.gluPersonnel_Personnel.EditValue =
                            openReqestInfo.Properties.Personnel_PersonnelTeacherKey.Value;
                    }
                    this.ckeTheory.Checked = openReqestInfo.Properties.Credit1.Value;
                    this.ckePractice.Checked = openReqestInfo.Properties.Credit3.Value;
                    this.ckeCreateSubjectClass.Checked = openReqestInfo.Properties.CreateSubjectClass.Value;

                    this.gluTraining_Class_Room.EditValue = openReqestInfo.Properties.Training_Class_RoomKey;
                    this.txtCredits.Text = openReqestInfo.Properties.Credits.ToString();
                    this.txtLessons.Text = openReqestInfo.Properties.Lessons.ToString();

                    this.m_iSession = openReqestInfo.Properties.Training_SessionKey.Value;
                    this.m_iDayOfWeek = openReqestInfo.Properties.Training_WeekDayKey.Value;
                    this.txtNote.Text = openReqestInfo.Properties.Note.ToString();
                    m_lIClassKey.Clear();
                    if (styleLoad == xucWeek.StyleLoad.JoinRequest)
                    {
                        listChildrend = new DataTable();
                        listChildrend =
                            this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequests.GetListChildrent(
                            iTraining_SubjectOpenRequestKey).ToDataTable();

                        if (listChildrend.Rows.Count > 0)
                        {
                            for (int i = 0; i < listChildrend.Rows.Count; i++)
                            {
                                DataTable listClass =
                                    this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequest_Teacher_Students.
                                        GetByReuqestOpenKey(
                                    this.m_dbTraining.m_DCReadOnly.Training_Classes,
                                    listChildrend.Rows[i]["Training_SubjectOpenRequestKey"].ToInt()).ToDataTable();
                                for (int j = 0; j < listClass.Rows.Count; j++)
                                {
                                    int classKey = listClass.Rows[j]["Training_ClassKey"].ToInt();
                                    string strID = listClass.Rows[j]["ID"].ToString();
                                    string strName = listClass.Rows[j]["Name"].ToString();
                                    string strTotals = listClass.Rows[j]["Totals"].ToString();
                                    dt.Rows.Add(classKey, strID, strName, strTotals, null);
                                    m_lIClassKey.Add(listClass.Rows[j]["Training_ClassKey"].ToInt());
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
        #endregion

        #region [Duyệt mở môn]
        private void btnAgree_Click(object sender, EventArgs e)
        {
            try
            {
                if (!SysUtils.CheckAccessByRule(Utils.Configs.RuleConfig.SUBJECTOPEN))
                {
                    //XtraMessageBox.Show("Bạn không có quyền này");
                    return;
                }
                Training_SubjectOpenRequestInfo requestInfo =
                    new Training_SubjectOpenRequestInfo(this.m_iTraining_SubjectOpeRequestKey);
                if (requestInfo.ExistInDatabase)
                {
                    requestInfo.Properties.Startus = (int)Startus.Agree;
                    requestInfo.Save();
                }
                #region [An - Lưu vào bản session subject class rom]
                DataTable m_tblsession =
                    m_dbTraining.m_DCReadOnly.Personnel_Personnel_Sessions.GetSession(
                    requestInfo.Properties.Training_SubjectOpenRequestKey).ToDataTable();
                if (m_tblsession.Rows.Count > 0)
                {
                    for (int i = 0; i < m_tblsession.Rows.Count; i++)
                    {
                        try
                        {
                            Training_Session_Subject_Class_RoomInfo sessionroominfo =
                                new Training_Session_Subject_Class_RoomInfo();

                            sessionroominfo.Properties.Training_SessionKey =
                                int.Parse(requestInfo.Properties.Training_SessionKey.ToString());

                            DataTable m_tbltable = new DataTable();
                            m_tbltable = m_dbTraining.m_DCReadOnly.Training_Subject_Classes.
                                    GetSubjectClassBySubjectOpenRequest(
                                requestInfo.Properties.Training_SubjectOpenRequestKey).ToDataTable();
                            sessionroominfo.Properties.Training_Subject_ClassKey =
                                int.Parse(m_tbltable.Rows[0]["Training_Subject_ClassKey"].ToString());
                            try
                            {
                                sessionroominfo.Properties.Training_Class_RoomKey =
                                    int.Parse(requestInfo.Properties.Training_Class_RoomKey.ToString());
                            }
                            catch { }
                            sessionroominfo.Properties.Catalogue_TermKey = 1;
                            sessionroominfo.Properties.Catalogue_SchoolYearKey = 1;
                            sessionroominfo.Properties.Personnel_PersonnelKey =
                                requestInfo.Properties.Personnel_PersonnelTeacherKey;
                            sessionroominfo.Properties.RegistTime =
                                (DateTime)m_tblsession.Rows[i]["RegistTime"];
                            sessionroominfo.Properties.Training_WeekDayKey =
                                int.Parse(requestInfo.Properties.Training_WeekDayKey.ToString());
                            sessionroominfo.Save();
                        }
                        catch { continue; }
                    }
                }
                #endregion

                LUI_BTN_OK.Visibility= DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                LUI_BTN_DEL.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                LUI_BTN_EDI.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                LUI_BTN_SEND.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                
                XtraMessageBox.Show("Hoàn thành");
            }
            catch
            {
            }
        }
        #endregion

        #region [Chuyển ngày]
        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (!SysUtils.CheckEditByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    //XtraMessageBox.Show("Bạn không có quyền này");
                    return;
                }
                using (FrmSchedule_SubEdit frm =
                    new FrmSchedule_SubEdit(
                        this.m_iTraining_SubjectOpeRequestKey))
                {
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        LoadExistData();
                        if (OnChangeDay != null) OnChangeDay(this);
                    }
                }
            }
            catch
            {
            }
        }
        #endregion

        #region [Khởi Tạo Hàm]
        private enum Style
        {
            New, LoadExist
        }

        private enum Startus
        {
            Request = 0, Agree = 1, Finish = 2
        }
        #endregion

        #region [Hàm sữ dụng]
        private void ChoseSubject()
        {
            //try
            {
                if (!SysUtils.CheckEditByRule("R023"))
                {
                    //XtraMessageBox.Show("Bạn không có quyền này");
                    return;
                }
                if (frm_SubjectRequestOpen_ChooseSubject == null)
                {
                    frm_SubjectRequestOpen_ChooseSubject = new FrmSchedule_SubChooseSubject();
                }


                frm_SubjectRequestOpen_ChooseSubject.CouserKey =
                    Cache.m_iCatalogue_CouserKey;
                frm_SubjectRequestOpen_ChooseSubject.DepartmentKey =
                    Cache.m_iCatalogue_DepartmentKey;
                frm_SubjectRequestOpen_ChooseSubject.MajorKey =
                    Cache.m_iCatalogue_MajorKey;
                frm_SubjectRequestOpen_ChooseSubject.TrainingProgramKey =
                    Cache.m_iTraining_TrainingProgramKey;

                frm_SubjectRequestOpen_ChooseSubject.ShowDialog();
                if (frm_SubjectRequestOpen_ChooseSubject.DialogResult == DialogResult.OK)
                {
                    string strSubjectName = frm_SubjectRequestOpen_ChooseSubject.strSubjectName;
                    int iSubjectKey = frm_SubjectRequestOpen_ChooseSubject.SubjectKey;
                    this.txtSubjectName.Text = strSubjectName;
                    this.m_strSubjectName = strSubjectName;
                    this.m_iTrainingSubjectKey = iSubjectKey;

                    //Training_SubjectInfo subjectInfo = new Training_SubjectInfo(iSubjectKey);
                    this.ckeTheory.Checked =
                        frm_SubjectRequestOpen_ChooseSubject.Credit1Checked;
                    this.ckePractice.Checked =
                        frm_SubjectRequestOpen_ChooseSubject.Credit3Checked;

                    this.ckeCreateSubjectClass.Checked =
                        frm_SubjectRequestOpen_ChooseSubject.CreateSubjectClass;
                    this.txtNote.Text =
                        frm_SubjectRequestOpen_ChooseSubject.Note;
                    this.txtCredits.Text =
                        frm_SubjectRequestOpen_ChooseSubject.Credit;
                    this.txtLessons.Text =
                        frm_SubjectRequestOpen_ChooseSubject.Lesson;
                    if (txtCredits.Text == "" && txtLessons.Text == "")
                    {
                        this.txtCredits.Text =
                            frm_SubjectRequestOpen_ChooseSubject.TotalsCredit.ToString();
                        this.txtLessons.Text =
                            (frm_SubjectRequestOpen_ChooseSubject.TotalsCredit * 15).ToString();
                    }
                    //this.ckeCreateSubjectClass.Checked = this.ckeTheory.Checked;
                    int depart = Convert.ToInt16(frm_SubjectRequestOpen_ChooseSubject.DepartmentKey.ToString());
                    layoutControl1.BackColor = SetCol(depart);
                }
            }
            //catch
            {
            }
        }

        private void ckeChose_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (OnChooseChange != null) OnChooseChange(this);
            }
            catch
            {
            }
        }

        private void ShowInfo()
        {
            try
            {
                if (this.m_style == Style.LoadExist)
                {
                    Training_SubjectOpenRequestInfo subjectOpenRequestInfo =
                        new Training_SubjectOpenRequestInfo(
                            this.m_iTraining_SubjectOpeRequestKey);
                    this.txtSubjectName.Enabled = false;
                    //Đã được duyệt
                    if (subjectOpenRequestInfo.Properties.Startus == (int)Startus.Agree)
                    {
                        LUI_BTN_DEL.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; //Ẩn nút xóa
                        LUI_BTN_OK.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; //Ẩn nút duyệt
                        LUI_BTN_SEND.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; //Ẩn nút gửi
                        LUI_BTN_EDI.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never; //Ẩn nút sửa
                    }
                    #region [Phân quyền]

                    #region [Người tạo]

                    #endregion

                    #region [Duyệt]

                    #region [Người ghép]

                    #endregion

                    #endregion

                    #region [Người chọn phòng]

                    #endregion

                    #endregion
                }
                if (this.m_style == Style.New)
                {

                }
            }
            catch
            {
            }
        }

        private void PermissionShow()
        {
            try
            {
                if (!SysUtils.CheckAddByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    this.btnSave.Enabled = false;
                }
                if (!SysUtils.CheckEditByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    this.btnEdit.Enabled = false;
                }
                if (!SysUtils.CheckDeleteByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    this.btnDelete.Enabled = false;
                }
                if (!SysUtils.CheckDeleteByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPENREQUEST))
                {
                    this.btnDelete.Enabled = false;
                }
                if (!SysUtils.CheckEditByRule(
                    Utils.Configs.RuleConfig.SUBJECTOPEN))
                {
                    this.btnAgree.Enabled = false;
                }
                if (!SysUtils.CheckEditByRule(
                    Utils.Configs.RuleConfig.JOINSUBJECTREQUESTOPEN))
                {
                    this.ckeChose.Enabled = false;
                }
            }
            catch
            {
            }
        }

        private Color SetCol(int depart = -1)
        {
            Color cl = new Color();

            if (depart == -1)
            {
                Training_SubjectOpenRequestInfo sj_op_re =
                    new Training_SubjectOpenRequestInfo(m_iTraining_SubjectOpeRequestKey);
                depart = Convert.ToInt16(
                    sj_op_re.Properties.Catalogue_DepartmentKey.ToString());
            }
            switch (depart)
            {
                case 6: cl = Color.LightCoral;
                    break;
                case 7: cl = Color.LightGreen;
                    break;
                case 8: cl = Color.LightSkyBlue;
                    break;
                case 9: cl = Color.LightPink;
                    break;
                case 10: cl = Color.Aqua;
                    break;
                case 11: cl = Color.LightGray;
                    break;
                case 12: cl = Color.MediumSpringGreen;
                    break;
                case 13: cl = Color.Wheat;
                    break;
                case 22: cl = Color.PaleGoldenrod;
                    break;
                default: cl = Color.Transparent;
                    break;
            }

            return cl;
        }

        #endregion

        #region [Sự Kiện]
        private void gluTraining_Class_Room_EditValueChanged(object sender, EventArgs e)
        {
            if (this.m_iTraining_SubjectOpeRequestKey != -1)
            {
                if (this.gluTraining_Class_Room.EditValue != null)
                {
                    Training_SubjectOpenRequestInfo info =
                        new Training_SubjectOpenRequestInfo(
                            this.m_iTraining_SubjectOpeRequestKey);
                    info.Properties.Training_Class_RoomKey =
                        (int)this.gluTraining_Class_Room.EditValue;
                    info.Save();
                }
            }
        }

        private void gluTraining_Class_Room_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (SysUtils.CheckAddByRule(
                Utils.Configs.RuleConfig.JOINSUBJECTREQUESTOPEN_ROOM))
            {
                this.gluTraining_Class_Room.GetData(
                    this.m_dbTraining.m_DCReadOnly.Training_Class_Rooms.GetClassRoomFree(
                        this.m_dbTraining.m_DCReadOnly.Training_SubjectOpenRequests,
                        this.m_iDayOfWeek + 1, this.m_iSession));
            }
        }

        private void btn_addSubject_Click(object sender, EventArgs e)
        {
            try
            {
                FrmPersonelList_SubInfo frm = new FrmPersonelList_SubInfo();
                frm.ShowDialog();

                this.LoadData();
                PermissionShow();
                this.btnDelete.Enabled = true;
                this.m_bDelete = true;
                this.btnEdit.Enabled = false;
                this.m_dStartTime = DteStart;
                this.m_dEndTime = DteEnd;
            }
            catch
            {
            }
        }

        private void btn_addPersionSession_Click(object sender, EventArgs e)
        {
            try
            {
                if (gluPersonnel_Personnel.EditValue == null)
                {
                    //FrmPersonnelRegistSubject frm = new FrmPersonnelRegistSubject();
                    //frm.ShowDialog();

                    this.LoadData();
                    PermissionShow();
                    this.btnDelete.Enabled = true;
                    this.m_bDelete = true;
                    this.btnEdit.Enabled = false;
                    this.m_dStartTime = DteStart;
                    this.m_dEndTime = DteEnd;
                }
                else
                {
                    if (txtSubjectName.Text != "")
                    {
                        DialogResult result = new DialogResult();
                        result = MessageBox.Show("Bạn Có Muốn Thêm Môn " + txtSubjectName.Text +
                                                 "\nCho Giảng Viên " + gluPersonnel_Personnel.SelectedText,
                                                 "Xác Nhận",
                                                 MessageBoxButtons.YesNo);

                        if (result == DialogResult.Yes)
                        {
                            Personnel_Personnel_Subject_ScheduleInfo ps = new
                                Personnel_Personnel_Subject_ScheduleInfo(
                                    gluPersonnel_Personnel.EditValue.ToString(),
                                    SubjectKey);
                        }
                    }
                    else
                    {
                        //FrmPersonnelRegistSubject frm = new FrmPersonnelRegistSubject();
                        //frm.ShowDialog();
                        this.LoadData();
                        PermissionShow();
                        this.btnDelete.Enabled = true;
                        this.m_bDelete = true;
                        this.btnEdit.Enabled = false;
                        this.m_dStartTime = DteStart;
                        this.m_dEndTime = DteEnd;
                    }
                }
            }
            catch
            {
            }
        }

        private void btn_addPersionSubject_Click(object sender, EventArgs e)
        {
            //try
            //{
            //    if (gluPersonnel_Personnel.EditValue == null)
            //    {
            //        FrmPersonnelRegistSession frm = new FrmPersonnelRegistSession();
            //        frm.ShowDialog();
            //        this.LoadData();
            //        PermissionShow();
            //        this.btnDelete.Enabled = true;
            //        this.m_bDelete = true;
            //        this.btnEdit.Enabled = false;
            //        this.m_dStartTime = DteStart;
            //        this.m_dEndTime = DteEnd;
            //    }
            //    else
            //    {
            //        FrmPersonnelRegistSession frm =
            //            new FrmPersonnelRegistSession(
            //               gluPersonnel_Personnel.EditValue.ToString(),
            //                m_dStartTime,
            //                m_dEndTime);
            //        frm.ShowDialog();


            //        this.LoadData();
            //        PermissionShow();
            //        this.btnDelete.Enabled = true;
            //        this.m_bDelete = true;
            //        this.btnEdit.Enabled = false;
            //        this.m_dStartTime = DteStart;
            //        this.m_dEndTime = DteEnd;
            //    }
            //}
            //catch
            //{
            //}
        }
        #endregion

        private void grvTraining_SubjectClass_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {

                Color col = Color.Transparent;
                int dep = -1;
                try
                {
                    dep =
                    Convert.ToInt16(
                    grvTraining_SubjectClass.GetRowCellDisplayText(
                        e.RowHandle,
                        gcldep).ToString());
                }
                catch
                {
                }
                col = SetCol(dep);
                e.Appearance.BackColor = col;

                this.grvTraining_SubjectClass.Appearance.FocusedRow.BackColor2 = col;
                this.grvTraining_SubjectClass.Appearance.FocusedRow.BackColor = col;
            }
        }

        private void txtSubjectName_DoubleClick(object sender, EventArgs e)
        {
            ChoseSubject();
        }

        private void buttonEdit1_ButtonClick(object sender, 
            DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ChoseSubject();
        }
    }
}
